import sys
import os
import wget
import requests
import webbrowser
import xml.etree.ElementTree as ET
from PySide2.QtWidgets import QPushButton,QApplication, QDialog,QFileDialog,QMainWindow,QLabel,QProgressBar,QDialogButtonBox,QVBoxLayout
from PySide2.QtCore import Slot,QProcess,QThreadPool,QCoreApplication
from MainWindow import Ui_MainWindow
class updateDialog(QDialog):
    def __init__(self):
        super().__init__()
        
        self.setWindowTitle("更新提示")
        QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel
        self.buttonBox = QDialogButtonBox(QBtn)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.layout = QVBoxLayout()
        message = QLabel("即将开始下载并更新，是否确定？")
        self.layout.addWidget(message)
        self.layout.addWidget(self.buttonBox)
        self.setLayout(self.layout)
class noupdateDialog(QDialog):
    def __init__(self):
        super().__init__()
        
        self.setWindowTitle("更新提示")
        QBtn = QPushButton("确认", self)
        QBtn.clicked.connect(self.close)
        
        self.layout = QVBoxLayout()
        message = QLabel("暂无可用更新，点击 确认 按钮关闭对话框！")
        self.layout.addWidget(message)
        self.layout.addWidget(QBtn)
        self.setLayout(self.layout)
        
class PBarDialog(QDialog):
    def __init__(self,  parent=None):
        super(PBarDialog, self).__init__(parent)
 
        # Qdialog窗体的设置
        self.resize(500, 32) # QDialog窗的大小
 
        # 创建并设置 QProcessbar
        self.progressBar = QProgressBar(self) # 创建
        self.progressBar.setMinimum(0) #设置进度条最小值
        self.progressBar.setMaximum(100)  # 设置进度条最大值
        self.progressBar.setValue(0)  # 进度条初始值为0
        self.progressBar.setGeometry(QRect(1, 3, 499, 28)) # 设置进度条在 QDialog 中的位置 [左，上，右，下]
        self.show()
 
    def setValue(self,value): # 设置总任务进度和子任务进度
        self.progressBar.setValue(value)

class Gui(QMainWindow):
    def __init__(self):
        super(Gui, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle("视频格式转换器")
        self.ui.SourcePath.setPlaceholderText("请输入或选择源视频位置")
        self.ui.DestPath.setPlaceholderText("请输入或选择视频保存位置")
        self.ui.ToMP4.setChecked(True)
        self.Selected_item="ToMP4"        
        self.DestPath="./"               
        self.SourcePath= "./"
        
        #self.threadpool = QThreadPool() 
        #self.checkUpdate()
        #接收标准输出
        self.process = QProcess(self)
        # QProcess emits `readyRead` when there is data to be read
        self.process.readyReadStandardError.connect(self.errorAccur)
        self.process.readyReadStandardOutput.connect(self.progress)

        # Just to prevent accidentally running multiple times
        # Disable the button when process starts, and enable it when it finishes
        self.process.started.connect(lambda:self.ui.btnTransform.setEnabled(False) )
        self.process.finished.connect(self.progressEnd)
        
        self.ui.ToMP4.toggled.connect(self.radioButtonStatus)
        self.ui.ToCD.toggled.connect(self.radioButtonStatus)
        self.ui.ToPPT.toggled.connect(self.radioButtonStatus)
        self.ui.GetAudio.toggled.connect(self.radioButtonStatus)
        
        
        self.ui.SourcePath.textChanged.connect(self.Source_changed)
        self.ui.DestPath.textChanged.connect(self.Dest_changed)
        
        self.ui.SourceButton.clicked.connect(self.getSourcePath)
        self.ui.DestButton.clicked.connect(self.getDestPath)
        
        self.ui.btnTransform.clicked.connect(self.Transform)
        self.ui.checkUpdate.clicked.connect(self.checkUpdate)
        self.ui.gotosavepath.clicked.connect(self.gotoSavePath)
        self.ui.menuhelp.triggered.connect(self.gotohelp)
 
 
    @Slot()
    def progressEnd(self):
        self.ui.btnTransform.setEnabled(True)
        self.ui.txtOutput.append("转换完成！")    
        self.ui.ToMP4.setEnabled(True)
        self.ui.ToCD.setEnabled(True)            
        self.ui.ToPPT.setEnabled(True)
        self.ui.GetAudio.setEnabled(True)
        
    @Slot()
    def errorAccur(self):
        data=str(self.process.readAllStandardError().data().decode('utf-8')).strip()
        self.ui.txtOutput.append(data)  

    @Slot()
    def progress(self):       
        
        dataOutput=str(self.process.readAllStandardOutput().data().decode('utf-8')).strip()
        self.ui.txtOutput.append(dataOutput)

    @Slot()
    def checkUpdate(self):
        rootpath=os.path.abspath("./")
        LocalDomTree = ET.parse(os.path.join(rootpath,"version_vc.xml"))
        LocalCollection = LocalDomTree.getroot()
        Localsofts = LocalCollection.findall("soft")

        remote=requests.get("http://dl.edtshare.com/version_vc.xml").text
        remoteCollection = ET.fromstring(remote)
        remotesofts = remoteCollection.findall("soft")
        update_list=[]
        
        task_name =remotesofts[0][0].text.strip()
        URL=remotesofts[0][2].text
        DST=os.path.join(rootpath,task_name)
            
        #比较version
        if Localsofts[0][1].text == remotesofts[0][1].text:
                #print("{} 无需更新".format(name))
            pass
        else:
            update_list.append([URL,DST,task_name])
        

        if update_list:
            dlg=updateDialog()
            dlg.show()
            if dlg.exec_():
                self.Pbar=PBarDialog()
                self.thread=downloadExe(*update_list)
                self.thread.Signals.progress.connect(self.updatePB)
                self.thread.Signals.task_name.connect(self.updateTask)
                self.thread.Signals.stop.connect(self.closePB)
                self.thread.Signals.isSetup.connect(self.startSetup)
                self.threadpool.start(self.thread)
        else:                        
            dlg = noupdateDialog()
            dlg.show()
            if dlg.exec_():
                pass
    @Slot()
    def updatePB(self,value):
        if value:
            self.Pbar.setValue(value)
    @Slot()
    def startSetup(self,isSetup):
        if isSetup:
            print(isSetup)            
            os.system(isSetup)
    @Slot()
    def updateTask(self,task_name):
        if task_name:
            self.Pbar.setWindowTitle("正在更新"+task_name+"......")
    @Slot()
    def closePB(self,stop):
        if stop:            
            self.Pbar.setWindowTitle("更新完成，即将关闭对话框！")
            time.sleep(2)
            self.Pbar.close()
            if os.path.exists("./version_vc.xml"):
                os.remove("./version_vc.xml")
                wget.download("http://dl.edtshare.com/version.xml","version_vc.xml")                 
            else:
                wget.download("http://dl.edtshare.com/version.xml","version_vc.xml")        

    
    @Slot()
    def Transform(self):
        self.ui.txtOutput.setText("")
        if self.ui.SourcePath.text() != "" and self.ui.DestPath.text() != "":
            if self.Selected_item == "ToMP4":
                command=['-y','-v','32','-threads','4','-i',self.SourcePath,'-c:a','aac','-c:v','h264',self.DestPath]
            elif self.Selected_item == "ToCD":
                command=['-y','-v','32','-threads','4','-i',self.SourcePath,'-c:a','aac','-c:v','h264','-b:v','4000k',self.DestPath]
            elif self.Selected_item == "ToPPT":
                
                command=['-y','-v','32','-threads','4','-i',self.SourcePath,'-c:a','wmav2','-c:v','wmv2',self.DestPath]
            elif self.Selected_item == "GetAudio":
                command=['-y','-v','32','-i',self.SourcePath,'-f','mp3','-vn',self.DestPath]
                         
            self.process.start('./lib/ffmpeg.exe',command)            
            self.ui.btnTransform.setEnabled(False)   
            self.ui.ToMP4.setEnabled(False)
            self.ui.ToCD.setEnabled(False)            
            self.ui.ToPPT.setEnabled(False)
            self.ui.GetAudio.setEnabled(False)

        

    
    @Slot()
    def radioButtonStatus(self):
        if self.ui.ToMP4.isChecked():
            self.Selected_item="ToMP4"           
       
            
        if self.ui.ToCD.isChecked():
            self.Selected_item="ToCD"

        
        if self.ui.ToPPT.isChecked():
            self.Selected_item="ToPPT"
        
        if self.ui.GetAudio.isChecked():
            self.Selected_item="GetAudio"


    @Slot()
    def Source_changed(self):
        self.SourcePath=self.ui.SourcePath.text()
        
    @Slot()
    def Dest_changed(self):
        self.DestPath=self.ui.DestPath.text()
    
    @Slot()    
    def getSourcePath(self):
        self.SourcePath = QFileDialog.getOpenFileName(self, "打开文件",
                                       "./",
                                        "Video Format File (*.mp4 *.avi *.flv *.mov *.mpeg);;All Files (*.*)")
        self.SourcePath=self.SourcePath[0]
        
        self.ui.SourcePath.setText(self.SourcePath)
        self.ui.SourcePath.setEnabled(True)
    
    @Slot()
    def gotoSavePath(self):
        if self.DestPath :
            DestDir,filename=os.path.split(self.DestPath)
            os.startfile(os.path.abspath(DestDir))
    @Slot()
    def gotohelp(self):
        if self.DestPath :
            webbrowser.open('http://www.edtshare.com/?p=1496')
    
    @Slot()    
    def getDestPath(self):
        if self.Selected_item=='ToMP4':
            self.DestPath = QFileDialog.getSaveFileName(self, "保存视频",
                                       "./video",
                                       "MP4 Format File (*.mp4)")
        if self.Selected_item=='ToCD':
            self.DestPath = QFileDialog.getSaveFileName(self, "保存视频",
                                       "./video",
                                       "MP4 Format File (*.mp4)")
        if self.Selected_item=='ToPPT':
            self.DestPath = QFileDialog.getSaveFileName(self, "保存视频",
                                       "./video",
                                       "WMV Format File (*.wmv)")
        if self.Selected_item=='GetAudio':
            self.DestPath = QFileDialog.getSaveFileName(self, "保存音频",
                                       "./audio",
                                       "mp3 Format File (*.mp3)")
        self.DestPath = self.DestPath[0]
        
        
        self.ui.DestPath.setText(self.DestPath)
        self.ui.DestPath.setEnabled(True)
        


        
if __name__ == "__main__":
    app=QApplication([])

    window = Gui()
    window.show()

    sys.exit(app.exec_())